<template>
    <div class="h-full flex flex-col w-full">
        <Editor id="myTinymce" placeholder="在这里输入文字" v-model="contentValue" :init="initOptions" tag-name="div" />
    </div>
</template>

<script setup>
import axios from "@/javascript/request/http";
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver/theme";
import "tinymce/icons/default";
import "tinymce/models/dom";

import "tinymce/plugins/image"; // 插入上传图片插件
import "tinymce/plugins/importcss"; //图片工具
// import 'tinymce/plugins/media' // 插入视频插件
import "tinymce/plugins/table"; // 插入表格插件
import "tinymce/plugins/lists"; // 列表插件
import "tinymce/plugins/fullscreen"; //全屏
import "tinymce/plugins/link"; //超链接
// import 'tinymce/plugins/preview' // 预览
import "tinymce/plugins/searchreplace"; //查询替换

//max端不支持ES11中promise.allSettled方法，手动添加一下
function handlePromise(promiseList) {
    return promiseList.map((promise) =>
        promise.then(
            (res) => ({ status: "ok", res }),
            (err) => ({ status: "not ok", err })
        )
    );
}
Promise.allSettled = function (promiseList) {
    return Promise.all(handlePromise(promiseList));
};
const emits = defineEmits(["update:value", "change"]);
const props = defineProps({
    value: String,
});
// 数据池
let state = reactive({
    contentValue: "",
    loading: false,
    initOptions: {
        height: 380,
        language_url: "tinymce/langs/zh-Hans.js",
        language: "zh-Hans",
        skin_url: "tinymce/skins/ui/oxide",
        plugins: "link image searchreplace table fullscreen",
        toolbar:
            "undo redo bold italic underline strikethrough alignleft aligncenter alignright lineheight forecolor backcolor removeformat link unlink image table fullscreen",
        branding: false,
        // 隐藏菜单栏
        menubar: false,
        // 是否显示底部状态栏
        statusbar: false,
        images_upload_base_path: "/api",
        paste_data_images: true,
        // convert_urls: false,
        // 初始化完成
        init_instance_callback: (editor) => {
            //console.log("富文本初始化完成====>");
        },
        // 此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
        // 如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
        images_upload_handler: (blobInfo, progress) => {
            return new Promise((resolve, reject) => {
                if (blobInfo.blob().size / 1024 / 1024 > 2) {
                    reject({
                        message: "上传失败，图片大小请控制在 5M 以内",
                        remove: true,
                    });
                    return;
                } else {
                    const formData = new FormData();
                    formData.append("file", blobInfo.blob());
                    axios
                        .postFile("/upload", formData, {
                            "Content-Type": "multipart/form-data",
                        })
                        .then((res) => {
                            if (res.success) {
                                resolve(res.data.fileUrl);
                            } else {
                                reject(
                                    "HTTP Error: 上传失败" + res.data.message
                                );
                                return;
                            }
                        })
                        .catch(() => {
                            reject("上传出错，服务器开小差了呢");
                            return;
                        });
                }
            });
        },
    },
});

watch(
    () => state.contentValue,
    (newvalue, oldvalue) => {
        emits("update:value", newvalue);
    },
    {
        deep: true,
    }
);

watch(
    () => props.value,
    (newvalue, oldvalue) => {
        state.contentValue = newvalue;
    },
    { immediate: true }
);

onMounted(async () => {
    tinymce.init({
        content_style:
            "img {max-width:100px;max-height:200px;vertical-align:top}",
    }); //初始化
});
onUnmounted(() => {
    tinymce.remove(); //销毁
});

//数据绑定
const { loading, initOptions, contentValue } = toRefs(state);
</script>
<style>
.tox-tinymce {
    border: 2px solid #fff !important;
    border-bottom-left-radius: 0 !important;
    border-bottom-right-radius: 0 !important;
}
.tox-tinymce .tox-tbtn {
    width: 30px;
}
</style>